/**
 * Copyright (C), 2011-2016 The Store
 * File Name: RegisterService.java
 * Encoding: UTF-8
 * Date: Feb 29, 2012
 * History: 
 */
package com.waynewan.qcomet.listener;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Wayne Wan(waynewan@mail.com)
 * @version Revision: 1.00 Date: Feb 29, 2012
 */
public class RegisterService {
	private static Log log = LogFactory.getLog(RegisterService.class);
	private static Map<String, String> LISTENERS_CLAZZ = new HashMap<String, String>();
	private static Map<String, AbstractListener> LISTENERS = new HashMap<String, AbstractListener>();
	
	/**
	 * register inner event listeners
	 */
	static{
		registerListener("genericEvent", "com.waynewan.qcomet.listener.GenericEventListener");
	}
	/**
	 * register a new event listener, normally new listener should be 
	 * registered before MessagePushServlet init.
	 * 
	 * @Title: registeListener
	 * @Description:
	 * @param 
	 * @return void
	 * @author Wayne Wan(waynewan@mail.com)
	 * @date  Feb 29, 2012
	 */
	public static void registerListener(String eventName, String clazz){
		if(LISTENERS_CLAZZ.get(eventName)!=null) throw new RuntimeException("event listener had been added yet!");
		LISTENERS_CLAZZ.put(eventName, clazz);
	}
	
	public static boolean isEventListenerExist(String eventName){
		return (LISTENERS.get(eventName)!=null);
	}
	
	public static AbstractListener getEventListener(String eventName){
		return LISTENERS.get(eventName);
	}
	
	/**
	 * Normally this method should only be called by MessagePushServlet during servlet initialize lifecycle 
	 * @Title: initListeners
	 * @Description:
	 * @param 
	 * @return void
	 * @author Wayne Wan(waynewan@mail.com)
	 * @date  Feb 29, 2012
	 */
	@SuppressWarnings("unchecked")
	public static void initListeners(ExecutorService threadPool){
		Set<String> eventNames = LISTENERS_CLAZZ.keySet();
		for(String eventName : eventNames){
			String clazz = LISTENERS_CLAZZ.get(eventName);
			try{
				Class<AbstractListener> lClass = (Class<AbstractListener>)Class.forName(clazz);
				Constructor<AbstractListener> constructor = lClass.getConstructor(ExecutorService.class);
				AbstractListener listener = constructor.newInstance(threadPool);
				LISTENERS.put(eventName, listener);
			}catch(Exception e){
				log.error("create [" + clazz + "] instance failed!" , e);
			}
		}
		
	}
}
